﻿using System;
using System.Collections;
using System.IO;
using System.Web;
using Brettle.Web.NeatUpload;
using mojoPortal.Business;
using mojoPortal.Web;
using mojoPortal.Web.Framework;
using Resources;



namespace ud_Gallery.UI
{

    public partial class BulkUploadPage : NonCmsBasePage
    {
        private int pageId = -1;
        private int moduleId = -1;
        private string imageFolderPath;
        private string fullSizeImageFolderPath;
        private GalleryConfiguration config = new GalleryConfiguration();
        private Hashtable moduleSettings;
       

        protected void Page_Load(object sender, EventArgs e)
        {
            LoadParams();

            if (!UserCanEditModule(moduleId, Gallery.FeatureGuid))
            {
                SiteUtils.RedirectToAccessDeniedPage(this);
                return;
            }

            LoadSettings();
            PopulateLabels();

            if (!IsPostBack)
            {
                if ((Request.UrlReferrer != null) && (hdnReturnUrl.Value.Length == 0))
                {
                    hdnReturnUrl.Value = Request.UrlReferrer.ToString();
                    lnkCancel.NavigateUrl = hdnReturnUrl.Value;
                }
            }

        }

       

        void btnUpload_Click(object sender, EventArgs e)
        {
            Module module = GetModule(moduleId, Gallery.FeatureGuid);

            if (module == null)
            {
                SiteUtils.RedirectToAccessDeniedPage(this);
                return;
            }

            SiteUser siteUser = SiteUtils.GetCurrentSiteUser();

            try
            {

                if (multiFile.Files.Length > 0)
                {

                    foreach (UploadedFile file in multiFile.Files)
                    {
                        if (file == null || file.FileName == null || file.FileName.Trim().Length <= 0) continue;
                        string ext = Path.GetExtension(file.FileName);
                        if (!SiteUtils.IsAllowedUploadBrowseFile(ext, ".jpg|.gif|.png|.jpeg")) continue;
                        GalleryImage galleryImage = new GalleryImage(moduleId, imageFolderPath)
                                                        {
                                                            ModuleGuid = module.ModuleGuid,
                                                            WebImageHeight = config.WebSizeHeight,
                                                            WebImageWidth = config.WebSizeWidth,
                                                            ThumbNailHeight = config.ThumbnailHeight,
                                                            ThumbNailWidth = config.ThumbnailWidth,
                                                            UploadUser = Context.User.Identity.Name
                                                        };

                        if (siteUser != null) galleryImage.UserGuid = siteUser.UserGuid;

                        //string destPath = fullSizeImageFolderPath + galleryImage.ImageFile;
                        //if (File.Exists(destPath))
                        //{
                        //    File.Delete(destPath);
                        //}
                        //file.MoveTo(destPath, MoveToOptions.Overwrite);

                        // 2010-02-12 change from previous implementation with ugly guid file names
                        string newFileName = Path.GetFileName(file.FileName).ToCleanFileName(WebConfigSettings.ForceLowerCaseForUploadedFiles);

                        if (galleryImage.ImageFile == newFileName)
                        {
                            // an existing gallery image delete the old one
                            if (File.Exists(fullSizeImageFolderPath + newFileName))
                            {
                                File.Delete(fullSizeImageFolderPath + newFileName);
                            }
                        }
                        else
                        {
                            // this is a new galleryImage instance, make sure we don't use the same file name as any other instance
                            int i = 1;
                            while (File.Exists(fullSizeImageFolderPath + newFileName))
                            {
                                newFileName = i.ToInvariantString() + newFileName;
                                i += 1;
                            }

                        }

                        string destPath = fullSizeImageFolderPath + newFileName;
                        file.MoveTo(destPath, MoveToOptions.Overwrite);

                        galleryImage.ImageFile = newFileName;
                        galleryImage.WebImageFile = newFileName;
                        galleryImage.ThumbnailFile = newFileName;

                        GalleryHelper.ProcessImage(galleryImage, file.FileName, config.ResizeBackgroundColor);
                    }
                }
                
                WebUtils.SetupRedirect(this, SiteUtils.GetCurrentPageUrl());

            }
            catch (UnauthorizedAccessException ex)
            {
                lblError.Text = ex.Message;
            }
            catch (ArgumentException ex)
            {
                lblError.Text = ex.Message;
            }


        }


        private void PopulateLabels()
        {
            Title = SiteUtils.FormatPageTitle(siteSettings, GalleryResources.BulkUploadHeading);

            btnAddFile.Text = GalleryResources.AddFileButton;
            btnUpload.Text = GalleryResources.BulkUploadButton;
            lnkCancel.Text = GalleryResources.GalleryEditCancelButton;
        }

        private void LoadSettings()
        {
           
            moduleSettings = ModuleSettings.GetModuleSettings(moduleId);
            config = new GalleryConfiguration(moduleSettings);
            

            lnkCancel.NavigateUrl = SiteUtils.GetCurrentPageUrl();

            mojoSetup.VerifyGalleryFolders(siteSettings.SiteId, moduleId);

            if (WebConfigSettings.ImageGalleryUseMediaFolder)
            {
                imageFolderPath = HttpContext.Current.Server.MapPath("~/Data/Sites/"
                    + siteSettings.SiteId.ToInvariantString() + "/media/GalleryImages/" + moduleId.ToInvariantString() + "/");
            }
            else
            {
                imageFolderPath = HttpContext.Current.Server.MapPath("~/Data/Sites/"
                    + siteSettings.SiteId.ToInvariantString() + "/GalleryImages/" + moduleId.ToInvariantString() + "/");
            }

            fullSizeImageFolderPath = imageFolderPath + "FullSizeImages" + Path.DirectorySeparatorChar;

            

        }

        private void LoadParams()
        {
            pageId = WebUtils.ParseInt32FromQueryString("pageid", pageId);
            moduleId = WebUtils.ParseInt32FromQueryString("mid", moduleId);

        }


        #region OnInit

        override protected void OnInit(EventArgs e)
        {
            base.OnInit(e);
            Load += Page_Load;
            btnUpload.Click += btnUpload_Click;
        }
        #endregion
    }
}
